<template>
  <div class="workshop-setting-container">
    <!-- 搜索表单 -->
    <div class="search-form" v-show="isSearchFormVisible">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="车间编码">
          <el-input
            v-model="searchForm.workshopCode"
            placeholder="请输入车间编码"
            clearable
            @keyup.enter="loadTableData"
          />
        </el-form-item>
        <el-form-item label="车间名称">
          <el-input
            v-model="searchForm.workshopName"
            placeholder="请输入车间名称"
            clearable
            @keyup.enter="loadTableData"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadTableData">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-bar">
      <div class="left-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
          <el-icon><Delete /></el-icon> 批量删除
        </el-button>
      </div>
      <div class="right-buttons">
        <el-button @click="toggleSearchForm">
          <el-icon><Search /></el-icon>
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
      border
      stripe
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="workshopCode" label="车间编码" min-width="120" align="center">
        <template #default="scope">
          <el-link type="primary" :underline="false" @click="handleView(scope.row)">
            {{ scope.row.workshopCode }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="workshopName" label="车间名称" min-width="150" align="center" />
      <el-table-column prop="area" label="面积" min-width="100" align="center" />
      <el-table-column prop="principal" label="负责人" min-width="120" align="center" />
      <el-table-column prop="status" label="是否启用" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="descs" label="备注" min-width="150" align="center" show-overflow-tooltip />
      <el-table-column label="操作" width="150" fixed="right" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)">修改</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加车间' : '编辑车间'"
      width="600px"
      :close-on-click-modal="false"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="车间编码" prop="workshopCode">
          <el-input
            v-model="formData.workshopCode"
            placeholder="请输入车间编码"
            :disabled="dialogType === 'edit'"
          >
            <template #append>
              <el-switch
                v-model="autoGenerate"
                active-text="自动生成"
                @change="handleAutoGenerateChange"
              />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="车间名称" prop="workshopName">
          <el-input v-model="formData.workshopName" placeholder="请输入车间名称" />
        </el-form-item>
        <el-form-item label="面积" prop="area">
          <el-input-number
            v-model.number="formData.area"
            :min="0"
            :precision="2"
            :step="1"
            style="width: 100%"
            placeholder="请输入面积"
            @change="val => formData.area = Number(val)"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="principal">
          <el-input 
            v-model="formData.principal" 
            placeholder="请输入负责人"
            clearable
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-radio-group v-model.number="formData.status">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="descs">
          <el-input
            v-model="formData.descs"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            clearable
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="查看车间"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="viewForm"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="车间编码" required>
          <el-input
            v-model="viewForm.workshopCode"
            disabled
          />
        </el-form-item>
        <el-form-item label="车间名称" required>
          <el-input
            v-model="viewForm.workshopName"
            disabled
          />
        </el-form-item>
        <el-form-item label="面积">
          <el-input-number
            v-model="viewForm.area"
            :min="0"
            :precision="2"
            :step="1"
            style="width: 100%"
            disabled
          />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input
            v-model="viewForm.principal"
            disabled
          />
        </el-form-item>
        <el-form-item label="是否启用" required>
          <el-radio-group v-model="viewForm.status" disabled>
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="viewForm.descs"
            type="textarea"
            :rows="3"
            disabled
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search, Refresh } from '@element-plus/icons-vue'
import http from '@/api/http'

// API endpoints
const API = {
  LIST: '/api/WorkshopSetting/GetWorkshopSettings',
  DELETE: '/api/WorkshopSetting/BatchDeleteWorkshopSettings',
  UPDATE: '/api/WorkshopSetting/UpdateWorkshopSetting',
  ADD: '/api/WorkshopSetting/AddWorkshopSetting'
}

// 响应式数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const submitLoading = ref(false)
const autoGenerate = ref(false)
const viewDialogVisible = ref(false)
const viewForm = reactive({
  workshopCode: '',
  workshopName: '',
  area: 0,
  principal: '',
  status: 1,
  descs: ''
})

// 表单数据
const formData = reactive({
  id: '',
  workshopCode: '',
  workshopName: '',
  area: 0,
  principal: '',
  status: 1,
  descs: ''
})

// 表单验证规则
const formRules = {
  workshopCode: [
    { required: true, message: '请输入车间编码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9_-]+$/, message: '车间编码只能包含字母、数字、下划线和横线', trigger: 'blur' }
  ],
  workshopName: [
    { required: true, message: '请输入车间名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入面积', trigger: 'blur' },
    { type: 'number', message: '面积必须为数字', trigger: 'blur' },
    { type: 'number', min: 0, message: '面积不能小于0', trigger: 'blur' }
  ],
  principal: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择是否启用', trigger: 'change' }
  ],
  descs: [
    { max: 200, message: '备注长度不能超过200个字符', trigger: 'blur' }
  ]
}

// 搜索表单
const searchForm = reactive({
  workshopCode: '',
  workshopName: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 控制搜索表单的显示/隐藏
const isSearchFormVisible = ref(true)

// 切换搜索表单显示/隐藏
const toggleSearchForm = () => {
  isSearchFormVisible.value = !isSearchFormVisible.value
}

// 刷新数据
const refreshData = () => {
  loadTableData()
}

// 生成随机车间编码
const generateWorkshopCode = () => {
  const randomNum = Math.floor(Math.random() * 900 + 100) // 生成100-999之间的随机数
  return `WS${randomNum}`
}

// 处理自动生成编码
const handleAutoGenerateChange = (val) => {
  if (val) {
    formData.workshopCode = generateWorkshopCode()
  } else {
    formData.workshopCode = ''
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: '',
    workshopCode: '',
    workshopName: '',
    area: 0,
    principal: '',
    status: 1,
    descs: ''
  })
  autoGenerate.value = false
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 构建提交的数据对象，确保所有字段都有正确的类型
        const submitData = {
          workshopCode: formData.workshopCode?.trim() || '',
          workshopName: formData.workshopName?.trim() || '',
          area: Number(formData.area || 0),
          principal: formData.principal?.trim() || '',
          status: Number(formData.status || 0),
          descs: formData.descs?.trim() || ''
        }

        // 如果是编辑模式，添加ID字段
        if (dialogType.value === 'edit' && formData.id) {
          submitData.id = formData.id
        }

        const url = dialogType.value === 'add' ? API.ADD : API.UPDATE
        const response = await http.post(url, submitData)
        
        if (response.status === true) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
          dialogVisible.value = false
          loadTableData()
        } else {
          throw new Error(response.message || (dialogType.value === 'add' ? '添加失败' : '修改失败'))
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error(error.message || '操作失败，请稍后重试')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      workshopCode: searchForm.workshopCode?.trim(),
      workshopName: searchForm.workshopName?.trim(),
      pageIndex: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    // 构建查询字符串
    const queryString = Object.entries(params)
      .filter(([_, value]) => value !== undefined && value !== '')
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&')

    console.log('请求URL:', `${API.LIST}?${queryString}`)
    const response = await http.get(`${API.LIST}?${queryString}`, null, true)
    console.log('API响应:', response)

    if (response?.status === true) {
      if (response.data?.list && Array.isArray(response.data.list)) {
        tableData.value = response.data.list
        pagination.total = response.data.total || response.data.list.length
      } else if (response.data?.rows && Array.isArray(response.data.rows)) {
        tableData.value = response.data.rows
        pagination.total = response.data.total || response.data.rows.length
      } else if (Array.isArray(response.data)) {
        tableData.value = response.data
        pagination.total = response.data.length
      } else {
        tableData.value = []
        pagination.total = 0
        ElMessage.warning('未查询到数据')
      }
    } else {
      throw new Error(response?.message || '获取数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '查询失败，请稍后重试')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 处理多选变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 处理查看
const handleView = (row) => {
  viewDialogVisible.value = true
  Object.assign(viewForm, {
    workshopCode: row.workshopCode || '',
    workshopName: row.workshopName || '',
    area: row.area || 0,
    principal: row.principal || '',
    status: row.status || 0,
    descs: row.descs || ''
  })
}

// 处理新增按钮点击
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  resetForm()
}

// 处理编辑按钮点击
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  resetForm()
  // 填充表单数据，确保所有字段都有值，使用Number类型转换确保数值类型正确
  Object.assign(formData, {
    id: row.id,
    workshopCode: row.workshopCode || '',
    workshopName: row.workshopName || '',
    area: Number(row.area || 0),
    principal: row.principal || '',
    status: Number(row.status || 0),
    descs: row.descs || ''
  })
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该记录吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        // 构建删除请求的URL，将id作为查询参数
        const ids = [row.id]
        const queryString = `?ids=${ids.join('&ids=')}`
        const response = await http.get(`${API.DELETE}${queryString}`)
        
        if (response.status === true) {
          ElMessage.success('删除成功')
          // 如果当前页只有一条数据，且不是第一页，则跳转到上一页
          if (tableData.value.length === 1 && pagination.currentPage > 1) {
            pagination.currentPage--
          }
          loadTableData()
        } else {
          throw new Error(response.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error(error.message || '删除失败，请稍后重试')
      }
    })
    .catch(() => {
      // 用户取消删除操作，不做任何处理
    })
}

// 批量删除选中的记录
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  ElMessageBox.confirm(`确认要删除选中的 ${selectedRows.value.length} 条记录吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const ids = selectedRows.value.map(item => item.id)
        const queryString = `?ids=${ids.join('&ids=')}`
        const response = await http.get(`${API.DELETE}${queryString}`)

        if (response.status === true) {
          ElMessage.success('删除成功')
          // 如果当前页数据全部删除，且不是第一页，则跳转到上一页
          if (tableData.value.length === ids.length && pagination.currentPage > 1) {
            pagination.currentPage--
          }
          loadTableData()
          // 清空选中状态
          selectedRows.value = []
        } else {
          throw new Error(response.message || '删除失败')
        }
      } catch (error) {
        console.error('批量删除失败:', error)
        ElMessage.error(error.message || '删除失败，请稍后重试')
      }
    })
    .catch(() => {
      // 用户取消删除操作，不做任何处理
    })
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadTableData()
}

// 处理重置
const handleReset = () => {
  searchForm.workshopCode = ''
  searchForm.workshopName = ''
  pagination.currentPage = 1
  loadTableData()
}

// 处理分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadTableData()
}

// 处理页码改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadTableData()
}

// 页面加载时获取数据
onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
.workshop-setting-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-buttons {
  display: flex;
  gap: 10px;
}

.right-buttons {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-tag) {
  min-width: 60px;
}

:deep(.el-button--link) {
  padding: 2px 0;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-pagination) {
  margin-top: 20px;
  justify-content: flex-end;
}

.dialog-form {
  padding: 20px;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}

.dialog-footer {
  padding: 20px;
  text-align: right;
}

/* 查看详情对话框中的禁用状态样式 */
:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
}

:deep(.el-radio.is-disabled) {
  cursor: not-allowed;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}
</style>
